<?php


namespace App\Logic;


use App\Base\ErrCode;
use App\Support\Database\DbManager;

class ArticleLogic
{
    public function getList()
    {
        set_time_limit(0);
        $piece = 10000;
        $yieldObj = $this->yieldGetList($piece);

        foreach ($yieldObj as $k => $rows) {
            $file = RUNTIME_PATH . DIRECTORY_SEPARATOR . 'export-'. $k . '-' .date('Ymd-His').'.txt';
            $f = fopen($file, 'a+');

            foreach ($rows as $row) {
                fwrite($f, json_encode($row, 256) . PHP_EOL);
            }
            fclose($f);
        }

        return [ErrCode::$successCode, [], ''];
    }

    public function yieldGetList($piece) {
        $db = DbManager::getInstance();
        $total = $db->getValue('select count(1) as total from article', 'total');
//        $total = 100;
        for ($i = 1; $i * $piece <= $total; $i++) {
            $offset = ($i - 1) * $piece;
            yield $db->all(
                "SELECT * FROM `article` ORDER BY `id` ASC limit $piece offset $offset"
            );
        }
    }

    public function insertArticle()
    {
        $db = DbManager::getInstance();
        $insertData = [];
        $dateTime = date('Y-m-d H:i:s');

        for ($i = 1; $i <= 20000; $i++) {
            $insertData[] = [
                'title'=> 'goodsssssssssssss'.$i,
                'author'=> '龙信红',
                'created_at' =>$dateTime,
                'content' => 'ajkfiejfagvaoigjagl;aije静安里个人名罢了ajkfiejfagvaoigjagl;aije静安里个人名罢了ajkfiejfagvaoigjagl;aije静安里个人名罢了ajkfiejfagvaoigjagl;aije静安里个人名罢了ajkfiejfagvaoigjagl;aije静安里个人名罢了ajkfiejfagvaoigjagl;aije静安里个人名罢了ajkfiejfagvaoigjagl;aije静安里个人名罢了ajkfiejfagvaoigjagl;aije静安里个人名罢了ajkfiejfagvaoigjagl;aije静安里个人名罢了ajkfiejfagvaoigjagl;aije静安里个人名罢了ajkfiejfagvaoigjagl;aije静安里个人名罢了ajkfiejfagvaoigjagl;aije静安里个人名罢了ajkfiejfagvaoigjagl;aije静安里个人名罢了',
            ];
        }
        $db->insertAll('article', $insertData);

        return [ErrCode::$successCode, [], ''];
    }
}